<template>
  <el-card class="box-card">
    <el-form
      ref="form"
    >
      <el-form-item label="课程" label-width="80px">
        <el-input disabled v-model="courseName"></el-input>
      </el-form-item>

      <el-form-item label="课时" label-width="80px">
        <el-input disabled v-model="theme"></el-input>
      </el-form-item>

      <el-form-item label="视频上传" label-width="80px">
        <input type="file" ref="video-file">
      </el-form-item>

      <el-form-item label="封面上传" label-width="80px">
        <input type="file" ref="image-file">
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleUpload">开始上传</el-button>
        <el-button>返回</el-button>
      </el-form-item>

      <el-form-item>
        <p v-if="uploadPercent !== 0">视频上传中: {{ uploadPercent }}%</p>
        <p v-if="isUploadSuccess">视频转码中：{{ isTranscodeSuccess ? '完成': '正在转码中...' }}</p>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
  import { getCourseById } from '@/services/course'
  import { getLessonById } from '@/services/lesson'
  import {
    aliyunImagUploadAddressAdnAuth,
    aliyunVideoUploadAddressAndAuth,
    aliyunTransCode,
    aliyunTransCodePercent
  } from '@/services/aliyun-upload'

  export default {
    name: 'UploadVideo',
    props: {
      courseId: {
        type: [Number, String],
        required: true,
      },
      lessonId: {
        type: [Number, String],
        required: true,
      }
    },
    data() {
      return {
        courseName: '',
        theme: '',
        uploader: null,
        imageURL: null,
        videoId: null,
        uploadPercent: 0,
        isUploadSuccess: false,
        isTranscodeSuccess: false,
      }
    },
    created() {
      this.loadData()
      this.initUploader()
    },
    methods: {
      async loadData() {
        const { code: code1, data: course } = await getCourseById(this.courseId)
        if (code1 === '000000') {
          this.courseName = course.courseName
        }

        const { code: code2, data: lesson } = await getLessonById(this.lessonId)
        if (code2 === '000000') {
          this.theme = lesson.theme
        }
      },
      handleUpload() {
        this.uploadPercent = 0
        this.isUploadSuccess = false
        this.isTranscodeSuccess = false
        const videoFile = this.$refs['video-file'].files[0]
        const imageFile = this.$refs['image-file'].files[0]
        // 要求图片在前、视频在后
        this.uploader.addFile(imageFile)
        this.uploader.addFile(videoFile)
        this.uploader.startUpload()
      },
      initUploader() {
        this.uploader = new window.AliyunUpload.Vod({
          // 阿里账号ID，必须有值
          userId: '1618139964448548',
          // 上传到视频点播的地域，默认值为'cn-shanghai'，//eu-central-1，ap-southeast-1
          region: '',
          // 分片大小默认1 MB，不能小于100 KB
          partSize: 1048576,
          // 并行上传分片个数，默认5
          parallel: 5,
          // 网络原因失败时，重新上传次数，默认为3
          retryCount: 3,
          // 网络原因失败时，重新上传间隔时间，默认为2秒
          retryDuration: 2,
          // 开始上传
          onUploadstarted: async uploadInfo => {
            if (uploadInfo.isImage) {
              // 图片 - 1. 获取凭证
              const { code, data } = await aliyunImagUploadAddressAdnAuth()
              if (code === '000000') {
                this.imageURL = data.imageURL
                // 2. 设置凭证，之后开始上传
                this.uploader.setUploadAuthAndAddress(uploadInfo, data.uploadAuth, data.uploadAddress, data.imageId)
              }
            } else {
              // 视频 - 1. 获取凭证
              const { code, data } = await aliyunVideoUploadAddressAndAuth({
                fileName: uploadInfo.file.name,
                imageUrl: this.imageURL
              })
              if (code === '000000') {
                this.videoId = data.videoId
                // 2. 设置凭证，之后开始上传
                this.uploader.setUploadAuthAndAddress(uploadInfo, data.uploadAuth, data.uploadAddress, data.videoId)
              }
            }
          },
          // 文件上传成功
          onUploadSucceed: function (uploadInfo) {
          },
          // 文件上传失败
          onUploadFailed: function (uploadInfo, code, message) {
          },
          // 文件上传进度，单位：字节
          onUploadProgress: (uploadInfo, totalSize, loadedPercent) => {
            if (!uploadInfo.isImage) {
              this.uploadPercent = Math.floor(loadedPercent * 100)
            }
          },
          // 全部文件上传结束
          onUploadEnd: async uploadInfo => {
            this.isUploadSuccess = true
            // 上传结束后开始转码
            const { code } = aliyunTransCode({
              lessonId: this.lessonId,
              coverImageUrl: this.imageURL,
              fileId: this.videoId,
              fileName: this.$refs['video-file'].files[0].name
            })
            if (code === '000000') {
              // 轮询转码进度
              const timer = setInterval(async () => {
                const { code, data } = await aliyunTransCodePercent(this.lessonId)
                if (code === '000000') {
                  if (data === 100) {
                    this.isTranscodeSuccess = true
                    this.$message.success('视频转码成功')
                    clearInterval(timer)
                  }
                }
              }, 1e3)
            }
          },
        })
      },
    }
  }
</script>
